<?php

class Handler_tool {

    /**
     * 数据转换
     * @para object $data 格式：
     *              object(stdClass)#6 (2) {
      ["columns"]=>
      array(3) {
      [0]=>
      string(10) "AirCompany"
      [1]=>
      string(8) "FlightNO"
      [2]=>
      string(3) "Org"
      }
      ["rows"]=>
      array(2) {
      [0]=>
      array(3) {
      [0]=>
      string(2) "MU"
      [1]=>
      string(6) "MU5695"
      [2]=>
      string(3) "PEK"
      }
      [1]=>
      array(3) {
      [0]=>
      string(2) "MU"
      [1]=>
      string(6) "MU5695"
      [2]=>
      string(3) "PEK"
      }
      }
      @return array
      {["AirCompany":"MU","FlightNO":"MU5695","Org":"PEK"],["AirCompany":"MU","FlightNO":"MU5695","Org":"PEK"]}
     */
    public static function dataTranslation($data) {
        $dataArrays = array();
        if (is_array($data->rows)) {
            foreach ($data->rows as $key => $oneData) {
                $dataArray = array();
                foreach ($data->columns as $key1 => $value1) {
                    $dataArray[$value1] = $oneData[$key1];
                }
                $dataArrays[] = $dataArray;
            }
        }

        return $dataArrays;
    }

    /**
     * 把机票后台的订单状态转换为前台的订单状态
     *
     * 后代代码：后台状态-前台状态
      0：已取消-已取消
      1、待确认-处理中
      2、待支付-待支付
      3、待出票-待出票
      11、已退票 -已退票
      12、改期等待-申请改期
      14、已废票 -已取消
      15、退票等待 -申请退票
      19：无效订单 -处理中
      20、已完成 -已出票
      32：废票等待 -处理中
      50：待确认特殊 -待确认
      51：待确认出票特殊 -待确认
      53：未完成-待支付
      54：手工取消PNR -已取消
      16：退款等待-处理中
      其他-处理中
     * 
      public static function flightStatusTranslation($status)
      {
      $frontStatus = "";
      switch ($status)
      {
      case 0:
      $frontStatus = "已取消";
      break;
      case 1:
      case 19:
      case 32:
      case 16:
      $frontStatus = "处理中";
      break;
      case 2:
      $frontStatus = "已提交支付";
      break;
      case 3:
      $frontStatus = "待出票";
      break;
      case 11:
      $frontStatus = "已退票";
      break;
      case 12:
      $frontStatus = "申请改期";
      break;
      case 14:
      $frontStatus = "已取消";
      break;
      case 15:
      $frontStatus = "申请退票";
      break;
      case 20:
      $frontStatus = "已出票";
      break;
      case 50:
      $frontStatus = "待确认";
      break;
      case 51:
      $frontStatus = "待确认";
      break;
      case 53:
      $frontStatus = "待支付";
      break;
      case 54:
      $frontStatus = "已取消";
      break;
      default:
      $frontStatus = "处理中";
      break;
      }
      return $frontStatus;
      }
     */
    /*
     * 根据传入舱位代码返回舱位名称
     */
    public static function getCabinName($cabin, $airCompany = "") {
        if (array_key_exists($airCompany, Flight_static::$airCompanyCabinName)) {
            $cabinName = Flight_static::$airCompanyCabinName[$airCompany][$cabin];
        }
        if (empty($cabinName)) {
            switch ($cabin) {
                case 'F':
                    $cabinName = '头等舱';
                    break;
                case 'C':
                    $cabinName = '公务舱';
                    break;
                default:
                    $cabinName = '经济舱';
                    break;
            }
        }
        return $cabinName;
    }

    /**
     * 返回乘客类型
     */
    public static function getPasengerTypeName($type) {
        $typeName = "成人";
        switch ($type) {
            case 1:
                $typeName = "成人";
                break;
            case 2:
                $typeName = "儿童";
                break;
            case 3:
                $typeName = "婴儿";
                break;
        }
        return $typeName;
    }

    /**
     * 根据支付方式代码，获取支付方式
     *
     *  //支付方式  0在线支付
      1票到付款
      2电话银行支付
      3银联.拉卡啦支付
      4信用卡支付
      5招商银行信用卡
      20集团客户票到付款
      21集团客户月结
     */
    public static function getPayMethodName($payMethod) {
        $payMethodName = "";
        switch ($payMethod) {
            case -1:
                $payMethodName = "缺省";
                break;
            case 0:
                $payMethodName = "网上支付";
                break;
            case 1:
                $payMethodName = "票到付款";
                break;
            case 2:
                $payMethodName = "电话银行支付";
                break;
            case 3:
                $payMethodName = "银联.拉卡啦支付";
                break;
            case 4:
                $payMethodName = "信用卡支付";
                break;
            case 5:
                $payMethodName = "招商银行信用卡";
                break;
            case 20:
                $payMethodName = "集团客户票到付款";
                break;
            case 21:
                $payMethodName = "集团客户月结";
                break;
        }
        return $payMethodName;
    }

    //把秒转换成"1小时50分"的格式
    public static function secondTimeToStr($iTime) {
        $minites = $iTime / 60;
        if (floor($minites / 60) == 0) {
            $sTime = $minites . "分钟";
        } else {
            $sTime = floor($minites / 60) . "小时";
            if ($minites % 60 != 0) {
                $sTime .= ($minites % 60) . "分";
            }
        }
        return $sTime;
    }

    //把证件类型代码转换为证件类型文字
    public static function certTypeToName($cert) {
        $certName = "";
        switch ($cert) {
            case 0:
                $certName = "身份证";
                break;
            case 1:
                $certName = "护照";
                break;
            case 2:
                $certName = "其他";
                break;
            default:
                $certName = "其他";
                break;
        }
        return $certName;
    }

    /**
     * 根据配送类型，取得配送名称
     * //配送类型   -1:不需要发票
      0：需要邮寄发票 - 平邮
      1：需要配送发票
      2：机场自取发票
      3.客人自取发票
      4.需要邮寄发票-挂号信
      5.需要邮寄发票-快递
     */
    public static function deliverTypeToName($deliver) {
        $deliverName = "";
        switch ($deliver) {
            case -1:
                $deliverName = "不需要发票";
                break;
            case 0:
                $deliverName = "平邮";
                break;
            case 1:
                $deliverName = "需要配送发票";
                break;
            case 2:
                $deliverName = "机场自取发票";
                break;
            case 3:
                $deliverName = "客人自取发票";
                break;
            case 4:
                $deliverName = "挂号信";
                break;
            case 5:
                $deliverName = "快递";
                break;
            default:
                $deliverName = "缺省";
                break;
        }

        return $deliverName;
    }

    /*
     * 传入生日　返回　１：成人２：儿童３：婴儿
     * 24个月内为婴儿
     * 12周岁内为儿童
     * 大于儿童为成人
     */

    public static function get_passenger_type_birthday($birthday, $get_date = "") {
        $re_type = 1;
        $re_month = 0;
        if ("" == $get_date || !strtotime($get_date)) {
            $get_date_str = date("Y-m-d");
        } else {
            $get_date_str = date("Y-m-d", strtotime($get_date));
        }
        $get_date_num = strtotime($get_date_str);
        if (strtotime($birthday) && strtotime($birthday) < $get_date_num) {
            $birthday_num = strtotime($birthday);
            $birthday_year = date("Y", $birthday_num);
            $birthday_month = date("m", $birthday_num);
            $birthday_day = date("d", $birthday_num);

            if (strtotime(($birthday_year + 2) . "-" . $birthday_month . "-" . $birthday_day) > $get_date_num) {
                $re_type = 3;
            } elseif (strtotime(($birthday_year + 12) . "-" . $birthday_month . "-" . $birthday_day) > $get_date_num) {
                $re_type = 2;
            }
        }
        return $re_type;
    }

    /*
     * 对数组进行格式化，生成字符串
     * 当$re_key为空时返回所有，否则按$re_key指定的下表内容进行返回
     */

    public static function get_str_form_arr($get_arr, $re_key = "") {
        $re_str = '';
        if ("" != $re_key) {
            $re_key_arr = explode(",", $re_key);
        } else {
            $re_key_arr = array();
        }

        if ('' != $get_arr && is_array($get_arr)) {
            foreach ($get_arr as $key => $value) {
                if ("" == $re_key ^ in_array($key, $re_key_arr)) {
                    if ('' != $re_str) {
                        $re_str .= ',';
                    }
                    $re_str .= $key . ':"' . $value . '"';
                }
            }
        }
        return $re_str;
    }

    /**
     * 检查请求是否合法，如果非法则拒绝请求且关闭当前窗口
     */
    public static function validateRequest() {
        //获取发起请求的页面地址
        $referer = empty($_SERVER["HTTP_REFERER"]) ? "" : trim($_SERVER["HTTP_REFERER"]);

        //获取当前页面的域名
        $pattern = "/" . preg_quote($_SERVER['SERVER_NAME']) . "/i";

        if (empty($referer) || !preg_match($pattern, $referer, $matches)) {
            //$this->alertAndClose("错误：非法URL提交页面！");
            return false;
        }
        return true;
    }

    /**
     * 弹出提示窗口
     * @param string $msg 提示的信息
     */
    public static function alert($msg) {
        if (!empty($msg)) {
            $script = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";
            $script .= "<script type='text/javascript'>\n";
            $script .= "alert('" . trim($msg) . "');\n";
            $script .= "</script>\n";
            echo $script;
        }
        exit();
    }

    /**
     * 弹出并返回
     * @param string $msg 提示的信息
     */
    public static function alertAndGoBack($msg) {
        if (!empty($msg)) {
            $script = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";
            $script .= "<script type='text/javascript'>\n";
            $script .= "alert('" . trim($msg) . "');\n";
            $script .= "history.go(-1);";
            $script .= "</script>\n";
            echo $script;
        }
        exit();
    }

    /**
     * 在页面上弹出提示窗口，用户点击确定后，页面自动跳转到指定的页面
     * @param string $msg 提示的信息
     * @param string $url 跳转的页面地址
     * @param string $top 跳出框架
     */
    public static function alertAndRedirect($msg, $url, $top = '') {
        if (!empty($msg) || !empty($url)) {
            $script = "<HTML><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><body>";
            $script .= "<script type='text/javascript'>\n";
            if (!empty($msg)) {
                $script .= "alert('" . trim($msg) . "');\n";
            }
            $script .= $top . "location.href='" . trim($url) . "';";
            $script .= "</script>\n</body></HTML>";
            echo $script;
        }
        exit();
    }

     public static function alertAndRedirectTop($msg, $url) {
        if (!empty($msg) || !empty($url)) {
            $script = "<HTML><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><body>";
            $script .= "<script type='text/javascript'>\n";
            if (!empty($msg)) {
                $script .= "alert('" . trim($msg) . "');\n";
            }
            $script .= "window.top.location.href='" . trim($url) . "';";
            $script .= "</script>\n</body></HTML>";
            echo $script;
        }
        exit();
    }
    /**
     * 通过输出script跳转到指定的页面
     * @param string $url 跳转的页面地址
     */
    public static function scriptRedirect($url) {
        if (!empty($url)) {
            $script = "<HTML><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><body>";
            $script .= "<script type='text/javascript'>\n";
            $script .= " location.href='" . trim($url) . "';";
            $script .= "</script>\n</body></HTML>";
            echo $script;
        }
        exit();
    }

    /**
     * 在页面上弹出提示窗口，用户单击确定后，关闭当前页面
     * @param string $msg 提示的信息
     */
    public static function alertAndClose($msg) {
        if (!empty($msg)) {
            $script = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";
            $script .= "<script language='javascript' type='text/javascript'>\n";
            $script .= "alert('" . trim($msg) . "');\n";
            $script .= "window.close();";
            $script .= "</script>\n";
            echo $script;
        }
        exit();
    }

    /*
     * 判断是否登录，如果没有登录则重新登录并返回到当前请求页面,如果已登录则返回到当前页面
     *
     * @param $member_info
     *
     */

    public static function checkLogin($member_info) {
        if (!$member_info->is_login) {
            $back_url = self::getWebrootPath() . $_SERVER['REQUEST_URI'];
            $url = SECUREURL . '/login/?backurl=' . $back_url;
            self::scriptRedirect($url);
        }
        return true;
    }

    /**
     * 服务器端页面跳转，如果页头已经输出则改为javascript的方式跳转
     * @param <string> $url 要跳转的url
     */
    public static function redirect($url) {
        if (!headers_sent()) {
            header('Location: ' . $url);
            exit;
        }
        //通过js方式跳转
        self::scriptRedirect($url);
    }

    /**
     * URL中是否已存在google utm信息
     * @param <string> $url 要检查的url
     * @return <bool> 存在返回true，否则返回false
     */
    public static function isUrlContainsUtmInfo($url) {
        $query = parse_url($url, PHP_URL_QUERY);
        if (empty($query)) {
            return false;
        }
        $query_element = explode($query, '&');
        foreach ($query_element as $value) {
            //判断url参数中是否存在utm信息
            if (strpos($value, 'utm_source=') !== false) {
                return true;
            }
        }
        return false;
    }

    /**
     * 从url地址中获取域名
     * @param <string> $url url地址
     */
    public static function getDomainFromUrl($url) {
        if (empty($url)) {
            return '';
        }
        //从URL里获取host
        preg_match('@^(?:http://|https://)?([^/]+)@i', $url, $matches);
        return $host = $matches[1];
    }

    /**
     * 校验传入的URL是否为etpass.com域名下的页面
     * @param <string> $url 要校验的url
     * @return <bool> 符合返回true，否则返回false
     */
    public static function isEtpassURL($url) {
        if (empty($url)) {
            return false;
        }
        $domain = self::getDomainFromUrl($url);
        return (stripos($domain, '.etpass.com') !== false) ? (stripos($domain, '.etpass.com.') !== false) ? false : true : false;
    }

    /**
     * 
     * 根据当前协议返回对应的webroot路径
     * @return <string> webroot路径
     */
    public static function getWebrootPath() {
        if ($_SERVER['SERVER_PORT'] == '443') {
            return SECUREURL;
        } else {
            return HTTPURL;
        }
    }

    /**
     *
     * 页面301跳转
     * @param <string> $url 跳转的url路径
     */
    public static function url301Redirect($url) {
        if (empty($url)) {
            return false;
        } else {
            header("HTTP/1.1 301 Moved Permanently");
            header("Location: $url");
        }
    }

    /**
     * 字符串加密解密
     * @param str $string 原文或密文
     * @param str $operation 操作(ENCODE | DECODE), 默认为 DECODE
     * @param str $key 密钥
     * @param int $expiry 密文有效期, 加密时候有效， 单位 秒，0 为永久有效
     * @return str  处理后的 原文或者 经过 base64_encode 处理后的密文
     */
    public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

        $ckey_length = 4;
        $key = md5($key ? $key : CRYPT_CODE_KEY);
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);

        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);

        $result = '';
        $box = range(0, 255);

        $rndkey = array();
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if ($operation == 'DECODE') {
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc . str_replace('=', '', base64_encode($result));
        }
    }

    /**
     * 转化国内手号有国家区号的号码为普通号码，
     * @param type $mobile
     * @return null 
     */
    public static function getSimpleCNMobile($mobile) {

        if (Handler_validate::checkSimpleCNPhone($mobile)) {
            return $mobile;
        } else {

            if (strpos($mobile, '-') !== FALSE) {
                $mobiles = explode('-', $mobile);
                if (Handler_validate::checkSimpleCNPhone($mobiles[1]))
                    return $mobiles[1];
                else
                    return NULL;
            }
        }
        return NULL;
    }

    /**
     * 格式化手机号码，有国家区号的，把00换成+。
     * 
     * @param str $mobile  一个合法的手机号码 (用户登录部分不能保证手机号码的合法性)
     * @return str 
     */
    public static function formatMobile($mobile) {

        if (Handler_validate::checkSimpleCNPhone($mobile)) {
            return $mobile;
        } else {
            $mobiles = self::getStdMobile($mobile);
            if (strcasecmp($mobiles['country_code'], '86') == 0 && Handler_validate::checkSimpleCNPhone($mobiles['mobile'])) {
                return $mobiles['mobile'];
            } elseif ($mobiles['country_code'] && $mobiles['mobile']) {
//                if ($login)
//                    return trim(implode('', $mobiles), '+');//国际手机号码去掉+号
//                else
                return implode('', $mobiles);
            }
        }

        return $mobile;
    }

    public static function getStdMobile($mobile) {
        $mobiles_re = array(
            'pre' => '+',
            'country_code' => '',
            'delimiter' => '-',
            'mobile' => ''
        );
        if (Handler_validate::checkSimpleINTERPhone($mobile)) {
            if (strpos($mobile, '-') !== FALSE) {
                $mobiles = explode('-', $mobile);
                if (strcasecmp(substr($mobiles[0], 0, 2), '00') == 0) {
                    $mobiles_re['country_code'] = substr($mobiles[0], 2);
                } elseif (strpos($mobiles[0], '+') !== FALSE) {
                    $mobiles_re['country_code'] = substr($mobiles[0], 1);
                }
                $mobiles_re['mobile'] = $mobiles[1];
            }
        }
        return $mobiles_re;
    }

    public static function ip2long($ip) {

        return sprintf("%u", ip2long($ip));
        ;
    }

    /**
     * 根据数组生成XML
     *  
     */
    public static function gen_xml_data($array_data) {
        $re_xml = '<?xml version="1.0" encoding="utf-8"?>';
        $re_xml .= '<root>';
        if (is_array($array_data)) {
            foreach ($array_data as $key => $value) {
                if (empty($value)) {
                    $re_xml .= '<' . $key . '/>';
                } else {
                    $re_xml .= '<' . $key . '>' . $value . '</' . $key . '>';
                }
            }
        }
        $re_xml .= '</root>';
        return $re_xml;
    }

    /**
     * 清除我的新订单数统计缓存
     * 
     * @param int $userid 用户ID; 
     * @return bool
     */
    public static function cleanMyOrderCount($userid) {
        //key 与 webroot/member/m_myEtpassOrderNum.php的key一值。
        $key = md5('my_order_count' . $userid);
        $cache = MemoryCache::getInstance();
        return $cache->delete($key);
    }
    
    /**
     * 输出一个png图片
     *  
     */
    public static function echoimage() {
        header("Content-type: image/png");

        //输出图片 
        $width = $height = 1;
        $checkimage = @imagecreate($width, $height);
        $back = imagecolorallocate($checkimage, 255, 255, 255);
        $border = imagecolorallocate($checkimage, 255, 255, 255);
        imagefilledrectangle($checkimage, 0, 0, $width - 1, $height - 1, $back); // 白色底
        imagerectangle($checkimage, 0, 0, $width - 1, $height - 1, $border);   // 黑色边框
        imagepng($checkimage);
        imagedestroy($checkimage);
    }

}

?>